import { getCache, setCache, removeCache } from '@/utils/session';
import { login, logout } from '@/api/user';
import { asyncRoutes } from '@/router/modules';
import { baseRoute, resetRouter } from '@/router';
import tenantApi from '@/api/system/tenant';
import userApi from '@/api/system/user';

//按钮权限
let permissions = [];
//第一个菜单信息
let firstMenu = {};
//处理路由信息
let { getRouters } = dealRemoteRouters();

const state = {
    accountInfo: '',
    userArea:getCache('userArea') || '',
    tenantInfo: getCache('tenantInfo') || '',
    isRoutersTag: false,
    token: getCache('TOKEN') || '',
    tenant: getCache('TENANT') || '',
    routes: baseRoute.concat(getRouters),
    homeRoute: getCache('homeRoute') || '',
    permissions: getCache('permissions') || [],
    flatRouters:[],
};

const mutations = {
    SET_TOKEN(state, token) {
        state.token = token;
    },
    SET_TENANT(state, tenant) {
        state.tenant = tenant;
    },
    SET_USERINFO(state, userInfo) {
        state.accountInfo = userInfo;
    },
    SET_TENANTINFO(state, tenantInfo) {
        state.tenantInfo = tenantInfo;
    },
    SET_STAGEACCOUNT(state, userInfo) {
        state.stageAccount = userInfo;
    },
    SET_ROUTE(state, route) {
        state.routes = baseRoute.concat(route);
    },
    SET_HOME(state,path){
        state.homeRoute = path;
    },
    SET_PERMISSIONS(state, permissions) {
        state.permissions = permissions;
    },
    SET_USERAREA(state,data){
        state.userArea = data
    },
    SET_FLATROUTERS(state,data){
        console.log(data)
        state.flatRouters = data;
    }
};

const actions = {
    login({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            let type = getCache('tenant') || 'master';
            login(type, userInfo)
                .then(async res => {
                    let { code, data } = res;
                    if (code == 200) {
                        commit('SET_TOKEN', data.token);
                        setCache('TOKEN', data.token);
                        let { companyCode, userId } = data.user;
                        let tenantResult = await tenantApi.remoteList({ companyCode, page: 1, size: 1 });
                        let userResult = await userApi.remoteList({ userId, page: 1, size: 1 });
                        let userInfo = userResult.data.list[0] || {};
                        let tenantInfo = tenantResult.data.list[0] || {};
                        let { getRouters, permissions ,homeRoute} = dealRemoteRouters(data.permissions);
                        setCache('userInfo', userInfo);
                        setCache('userArea', data.user);
                        setCache('tenantInfo', tenantInfo);
                        setCache('permissions', permissions);
                        commit('SET_PERMISSIONS', permissions);
                        commit('SET_USERAREA', data.user);
                        commit('SET_ROUTE', getRouters);
                        commit('SET_HOME', homeRoute);
                        commit('tagsView/ADD_TAGS', firstMenu, { root: true });
                        resolve({ res, routers: getRouters, userInfo: userInfo });
                        if(!homeRoute){
                            reject();
                        }
                    } else {
                        reject(res);
                    }
                })
                .catch(err => {
                    console.log(err);
                    reject(err);
                });
        });
    },
    getUserInfo({ commit, state }) {
        let userInfo = getCache('userInfo') || '';
        commit('SET_USERINFO', userInfo);
        commit('tagsView/ADD_TAGS', firstMenu, { root: true });
        return userInfo;
    },
    //isApi:是否需要调用退出接口
    logout({ commit }, isApi = true) {
        return new Promise(async (resolve, reject) => {
            let res = null;
            try {
                if (isApi) {
                    res = await logout();
                }
                commit('SET_TOKEN', '');
                commit('SET_USERINFO', '');
                commit('SET_STAGEACCOUNT', null);
                commit('SET_ROUTE', '');
                removeCache('TOKEN');
                removeCache('userInfo');
                removeCache('permissions');
                removeCache('routers');
                resetRouter();
                resolve();
            } catch (err) {
                reject(err);
            } finally {
            }
        });
    },
    removeRouter({ commit }) {
        return new Promise((resolve, reject) => {
            commit('SET_ROUTE', []);
            resolve([]);
        });
    },
    updateInfo({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            commit('SET_USERINFO', userInfo);
            resolve();
        });
    }
};

//处理需要的路由形式
export function dealRemoteRouters(permission) {
    let permissionBox = [];
    if (permission && permission.length) {
        permission.map(item => {
            let getItem = JSON.parse(item);
            permissionBox.push(getItem);
        });
        setCache('routers', permissionBox);
    } else {
        permissionBox = getCache('routers') || [];
    }
    permissions = [];
    let result = dealPermissions(permissionBox);
    let homeRoute = getFirstMenu(result[0]);
    if(homeRoute && homeRoute.path){
        if(homeRoute.path.indexOf('/dashboard')!=-1 && result.length!=1){
            homeRoute = getFirstMenu(result[1]);
        }
        setCache('homeRoute', homeRoute.path);
    }
    let getRouters = asyncRoutes(result, homeRoute.path);
    return { getRouters:getRouters,routers:result, permissions,homeRoute: homeRoute.path};
}

//处理用户菜单中权限信息
export function dealPermissions(permissionBox) {
    if (!permissionBox || !permissionBox.length) return [];
    permissionBox.map(item => {
        item.name = item.menuName;
        item.meta = { title: item.menuName, icon: item.icon };
        if (item.menuType == 'M') {
            let res = getFirstMenu(item);
            item.redirect = res.path || '/';
        }
        if (item.children && item.children.length) {
            item.children = dealPermissions(item.children);
        } else {
            item.children = null;
        }
        if (item.menuType == 'F') {
            permissions.push(item.path);
        }
        if (item.menuType == 'C') {
            if (hasChildren(item)) {
                item.children = null;
            }else{
                item.children = (item && item.children) && item.children.filter(child=>child.menuType=='C')
            }
            item.hidden = item.extendone == 'false' ? false : true;
            item.component = () => import('@/views' + item.path);
        }
    });
    return permissionBox;
}

function hasChildren(item) {
    return (item && item.children) && !item.children.some(item => item.extendone == 'true')
}

//权限菜单中第一个实质性的菜单
export function getFirstMenu(item) {
    if (!item) return {};
    if (item.menuType == 'C') {
        return item;
    }
    if (item.menuType == 'M') {
        let getItem = item?.children.find(menu => menu.menuType == 'C');
        if (getItem) {
            return getFirstMenu(item.children[0]);
        } else {
            return item;
        }
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
